package com.example.shopping_mall.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.shopping_mall.R;
import com.example.shopping_mall.adapter.BrandAdapter;
import com.example.shopping_mall.adapter.GoodFreshAdapter;
import com.example.shopping_mall.adapter.RecommendAdapter;
import com.example.shopping_mall.adapter.SecondAdapter;
import com.example.shopping_mall.base.KillDetailActivity;
import com.example.shopping_mall.base.ProductIntroductionActivity;
import com.example.shopping_mall.base.RecommendMoreActivity;
import com.example.shopping_mall.base.RecommendDetailActivity;
import com.example.shopping_mall.bean.BannerBean;
import com.example.shopping_mall.bean.BrandBean;
import com.example.shopping_mall.bean.BrandMiddleBean;
import com.example.shopping_mall.bean.GoodFreshBean;
import com.example.shopping_mall.bean.KillDetailBean;
import com.example.shopping_mall.bean.RecommendBean;
import com.example.shopping_mall.bean.SecondBean;
import com.example.shopping_mall.bean.SecondLastBean;
import com.example.shopping_mall.bean.UiBannerBean;
import com.example.shopping_mall.bean.UiBrandBean;
import com.example.shopping_mall.bean.UiGoodFreshBean;
import com.example.shopping_mall.bean.UiKillDetailBean;
import com.example.shopping_mall.bean.UiRecommendBean;
import com.example.shopping_mall.bean.UiSecondBean;
import com.example.shopping_mall.http.ShoppingRequest;
import com.example.shopping_mall.utils.ShoppingUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ShoppingMall_home_Fragment extends AllFragment {

    private static final String TAG =ShoppingMall_home_Fragment.class.getSimpleName();

    private ShoppingRequest shoppingRequest;
    List<UiBannerBean> bannerBeanList;
    Banner banner;
    int j=-1;

    //品牌制造商
    RecyclerView brandRecyclerView;
    List<UiBrandBean> beanArrayList;
    BrandAdapter brandAdapter;
    ImageView brand_image;
    int brandId;

    //秒杀专区
    RecyclerView secondRecyclerView;
    List<UiSecondBean> secondBeanList;
    SecondAdapter secondAdapter;
    ImageView seckillImage;

    //24小时换算成毫秒;2小时
    private int timeStemp = 7200000;
    private CountDownTimer timer;
    private TextView textView;
    private TextView textView2;
    private TextView textView3;

    //新鲜好物
    RecyclerView goodRecyclerView;
    List<UiGoodFreshBean> freshBeanList;
    GoodFreshAdapter freshAdapter;
    ImageView goodimage;

    //人气推荐
    List<UiRecommendBean> beanList;
    RecommendAdapter adapter;
    RecyclerView recyclerView;
    UiRecommendBean bean;
    ImageView recommendimage;

    //品牌更多推荐
    TextView more_recommended;

    //秒杀详情页
    TextView second_kill;

    @Override
    protected void initView() {
        shoppingRequest=new ShoppingUtils();

        //轮播图
        banner=findViewById(R.id.banner);
        bannerBeanList=new ArrayList<>();
        shoppingRequest.requestAdvertise(1,new ShoppingUtils.OnHomeAdvertiseRequestListener() {
            @Override
            public void OnHomeAdvertiseRequest(BannerBean[] bannerBeans) {
                for (int i=0;i<bannerBeans.length;i++) {
                        UiBannerBean  bannerBean = new UiBannerBean();
                        bannerBean.setImage(bannerBeans[i].getPic());
                        //Log.d(TAG, "OnPolicyRequest: " + bannerBean);
                        bannerBeanList.add(bannerBean);
                        //Log.d(TAG, "list: " + bannerBeanList);
                }

                //设置banner样式
                    banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                    //设置banner动画效果
                    banner.setBannerAnimation(Transformer.DepthPage);
                    //设置图片加载器
                    banner.setImageLoader(new MyLoader());
                    //设置图片集合
                    banner.setImages(bannerBeanList);
                    //设置自动轮播，默认为true
                    banner.isAutoPlay(true);
                    //设置轮播时间
                    banner.setDelayTime(2000);
                    //小点点居中
                    banner.setIndicatorGravity(BannerConfig.CENTER);
                    //banner设置方法全部调用完毕时最后调用
                    banner.start();
            }
        });


        //品牌制造商
        brandRecyclerView=findViewById(R.id.brand_recyclerView);
        beanArrayList=new ArrayList<>();
        brandAdapter=new BrandAdapter(getContext());
        //网格布局
        brandRecyclerView.setLayoutManager(new GridLayoutManager(getContext(),2,GridLayoutManager.VERTICAL,false));

        shoppingRequest.requestBrandApp(1, new ShoppingUtils.OnHomeBrandAppRequestListener() {
            @Override
            public void OnHomeBrandAppRequest(BrandMiddleBean[] middleBeans) {
                for (int i=0;i<middleBeans.length;i++) {
                    BrandBean brandBean=middleBeans[i].getPmsBrand();

                    UiBrandBean uiBrandBean = new UiBrandBean();

                    uiBrandBean.setMaker(middleBeans[i].getBrandName());
                    //Log.d(TAG, "OnPolicyRequest00: " + middleBeans[i].getBrandName());

                    int brand = i;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap brandbitmap;
                            try {
                                URL url = new URL(brandBean.getLogo());
                                //Log.d(TAG, "图片"+brandBean.getLogo());
                                //创建连接方法
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                //读取超时时长，即链接成功后，服务器返回时间
                                connection.setReadTimeout(5000);
                                //连接超时时长，连接服务器超时时间
                                connection.setConnectTimeout(5000);
                                //设置连接
                                connection.connect();
                                //返回结果码
                                //Log.d(TAG, "1111111111");
                                //final int responseCode = connection.getResponseCode ( );
                                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                    InputStream inputStream = connection.getInputStream();//得到数据流
                                    brandbitmap = BitmapFactory.decodeStream(inputStream);//将流转为bitmap

                                    brandRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                                        @Override
                                        public void onGlobalLayout() {
                                            View view=brandRecyclerView.getLayoutManager().findViewByPosition(brand);

                                            brand_image=view.findViewById(R.id.brand_image);

                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    brand_image.setImageBitmap(brandbitmap);
//                                                Log.d(TAG, "000000000000"+finalI);
                                                    //Log.d(TAG, "222222222222"+bitmap);
                                                }
                                            });

                                            //使用完移除监听器
                                            brandRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                                        }
                                    });

                                } else {
                                    Log.d(TAG, "抱歉，出错了");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                    beanArrayList.add(uiBrandBean);
                    //Log.d(TAG, "brandBean11: " + brandBean);
                }
                brandAdapter.setBrandBeans(beanArrayList);
                brandRecyclerView.setAdapter(brandAdapter);
            }
        });


        //秒杀专区
        secondRecyclerView=findViewById(R.id.second_kill_recyclerView);
        secondBeanList=new ArrayList<>();
        secondAdapter=new SecondAdapter(getContext());
        //网格布局
        secondRecyclerView.setLayoutManager(new GridLayoutManager(getContext(),2,GridLayoutManager.VERTICAL,false));

        textView=findViewById(R.id.hour);
        textView2=findViewById(R.id.minute);
        textView3=findViewById(R.id.second);


//        shoppingRequest.requestProductRelation(new ShoppingUtils.OnPromotionProductRelationRequestListener() {
//            @Override
//            public void OnPromotionProductRelationAppRequest(SecondLastBean lastBeans) {
//                SecondBean secondBeans=lastBeans.getProduct();
//                //for (int i=0;i<secondBeans.get;i++){
//                    Log.d(TAG, "OnPromotionProductRelationAppRequest: "+secondBeans.getBrandName());
//                //}
//            }
//        });

        shoppingRequest.requestProductRelation(new ShoppingUtils.OnPromotionProductRelationRequestListener() {
            @Override
            public void OnPromotionProductRelationAppRequest(SecondLastBean[] lastBeans) {
                for (int i=0;i<lastBeans.length;i++) {
                    SecondBean secondBeans=lastBeans[i].getProduct();
                    UiSecondBean uiSecondBean=new UiSecondBean();
                    uiSecondBean.setPriceSpike(secondBeans.getPrice());
                    uiSecondBean.setCommodity(secondBeans.getName());
                    uiSecondBean.setCommodityDetail(secondBeans.getDescription());
                    uiSecondBean.setRightprice(secondBeans.getPrice());
                    //Log.d(TAG, "zzzzznznznznnzn9999: "+secondBeans.getBrandName());

                    int second = i;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap secondbitmap;
                            try {
                                URL url = new URL(secondBeans.getPic());
                                //Log.d(TAG, "图片"+secondBeans.getPic());
                                //创建连接方法
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                //读取超时时长，即链接成功后，服务器返回时间
                                connection.setReadTimeout(5000);
                                //连接超时时长，连接服务器超时时间
                                connection.setConnectTimeout(5000);
                                //设置连接
                                connection.connect();
                                //返回结果码
                                //Log.d(TAG, "1111111111");
                                //final int responseCode = connection.getResponseCode ( );
                                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                    InputStream inputStream = connection.getInputStream();//得到数据流
                                    secondbitmap = BitmapFactory.decodeStream(inputStream);//将流转为bitmap

                                    secondRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                                        @Override
                                        public void onGlobalLayout() {
                                            View view=secondRecyclerView.getLayoutManager().findViewByPosition(second);

                                            seckillImage=view.findViewById(R.id.seckill_image);

                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    seckillImage.setImageBitmap(secondbitmap);
//                                                Log.d(TAG, "000000000000"+finalI);
                                                    //Log.d(TAG, "222222222222"+secondbitmap);
                                                }
                                            });

                                            //使用完移除监听器
                                            secondRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                                        }
                                    });

                                } else {
                                    Log.d(TAG, "抱歉，出错了");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                    secondBeanList.add(uiSecondBean);
                }
                secondAdapter.setSecondBeans(secondBeanList);
                secondRecyclerView.setAdapter(secondAdapter);
            }
        });


        //新鲜好物
        goodRecyclerView=findViewById(R.id.good_fresh_recyclerView);
        freshBeanList=new ArrayList<>();
        freshAdapter=new GoodFreshAdapter(getContext());
        goodRecyclerView.setLayoutManager(new GridLayoutManager(getContext(),2,GridLayoutManager.VERTICAL,false));

        shoppingRequest.requestNewProductPic(1, new ShoppingUtils.OnNewProductPicRequestListener() {
            @Override
            public void OnNewProductRequest(GoodFreshBean[] goodFreshBeans) {
                for (int i=0;i<goodFreshBeans.length;i++) {
                    UiGoodFreshBean freshBean = new UiGoodFreshBean();

                    freshBean.setGoodfreshCommodity(goodFreshBeans[i].getProductName());
                    freshBean.setGoodfreshPrice(goodFreshBeans[i].getPrice());

                    int good = i;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap goodbitmap;
                            try {
                                URL url = new URL(goodFreshBeans[good].getPic());
                                //Log.d(TAG, "图片"+goodFreshBeans[good].getPic());
                                //创建连接方法
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                //读取超时时长，即链接成功后，服务器返回时间
                                connection.setReadTimeout(5000);
                                //连接超时时长，连接服务器超时时间
                                connection.setConnectTimeout(5000);
                                //设置连接
                                connection.connect();
                                //返回结果码
                                //Log.d(TAG, "1111111111");
                                //final int responseCode = connection.getResponseCode ( );
                                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                    InputStream inputStream = connection.getInputStream();//得到数据流
                                    goodbitmap = BitmapFactory.decodeStream(inputStream);//将流转为bitmap

                                    goodRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                                        @Override
                                        public void onGlobalLayout() {
                                            View view=goodRecyclerView.getLayoutManager().findViewByPosition(good);

                                            goodimage=view.findViewById(R.id.good_fresh_things_image);

                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    goodimage.setImageBitmap(goodbitmap);
//                                                Log.d(TAG, "000000000000"+finalI);
                                                    //Log.d(TAG, "222222222222"+goodbitmap);
                                                }
                                            });

                                            //使用完移除监听器
                                            goodRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                                        }
                                    });

                                } else {
                                    Log.d(TAG, "抱歉，出错了");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                    freshBeanList.add(freshBean);
                }
                freshAdapter.setFreshBeanList(freshBeanList);
                goodRecyclerView.setAdapter(freshAdapter);
            }
        });


        //人气推荐
        recyclerView=findViewById(R.id.recommend_recyclerView);
        beanList=new ArrayList<>();
        adapter=new RecommendAdapter(getContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        shoppingRequest.requestRecommendProductPic(new ShoppingUtils.OnRecommendProductPicRequestListener() {
            @Override
            public void OnRecommendProductPicRequest(RecommendBean[] beans) {
                    for (int i = 0; i < beans.length; i++) {
                    bean=new UiRecommendBean();

                    bean.setRecommendname(beans[i].getProductName());
                    bean.setRecommendprice(beans[i].getPrice());
                    //Log.d(TAG, "图片"+beans[i].getPrice());

                        int finalI = i;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap bitmap;
                                try {
                                    URL url = new URL(beans[finalI].getPic());
                                    //Log.d(TAG, "图片"+beans[finalI].getPic());
                                    //创建连接方法
                                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                    //读取超时时长，即链接成功后，服务器返回时间
                                    connection.setReadTimeout(5000);
                                    //连接超时时长，连接服务器超时时间
                                    connection.setConnectTimeout(5000);
                                    //设置连接
                                    connection.connect();
                                    //返回结果码
                                    //Log.d(TAG, "1111111111");
                                    //final int responseCode = connection.getResponseCode ( );
                                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                        InputStream inputStream = connection.getInputStream();//得到数据流
                                        bitmap = BitmapFactory.decodeStream(inputStream);//将流转为bitmap

                                        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                                            @Override
                                            public void onGlobalLayout() {
                                                View view=recyclerView.getLayoutManager().findViewByPosition(finalI);

                                                recommendimage=view.findViewById(R.id.recommend_item_image);

                                            getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                recommendimage.setImageBitmap(bitmap);
//                                                Log.d(TAG, "000000000000"+finalI);
                                                //Log.d(TAG, "222222222222"+bitmap);
                                            }
                                        });

                                                //使用完移除监听器
                                                recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                                            }
                                        });

                                    } else {
                                        Log.d(TAG, "抱歉，出错了");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();

                        beanList.add(bean);
                        //Log.d(TAG, "beanList"+beanList);
                }
                adapter.setRecommendBeanList(beanList);
                recyclerView.setAdapter(adapter);
            }
        });


        TextView begin_text=findViewById(R.id.begin_text);
        //秒杀专区场次表
        shoppingRequest.requestPromotionSession(new ShoppingUtils.OnFlashPromotionSessionRequestListener() {
            @Override
            public void OnFlashPromotionSessionRequest(KillDetailBean[] detailBeans) {
                for (int i = 0; i < detailBeans.length; i++) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
                    try {
                        Date thisTime= dateFormat.parse(new SimpleDateFormat("HH:mm").format(new Date()));
                        Date startTime= dateFormat.parse(detailBeans[i].getStartTime().substring(11,16));
                        Date endTime= dateFormat.parse(detailBeans[i].getEndTime().substring(11,16));

                        if (thisTime.getTime()>endTime.getTime()) {
                        }else if (startTime.getTime()<=thisTime.getTime() && thisTime.getTime()<=endTime.getTime()) {
                            SimpleDateFormat dateFormat2 = new SimpleDateFormat("mm");
                            Date s=dateFormat2.parse(new SimpleDateFormat("mm").format(new Date()));
                            timer = new CountDownTimer(timeStemp, 1000) {
                                @Override
                                public void onTick(long l) {

                                    long day = l / (1000 * 24 * 60 * 60); //单位天
                                    long hour = (l - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60); //单位时
                                    long minute = (l - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60); //单位分
                                    long second2 = (l - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;//单位秒

                                    //long a=s.getTime()/(1000 * 60);
                                    textView.setText(hour+"");
                                    textView2.setText(minute-s.getTime()/(1000 * 60)+"");
                                    textView3.setText(second2+"");
                                }

                                @Override
                                public void onFinish() {

                                    //倒计时为0时执行此方法

                                }
                            };
                            timer.start();

                        }else if (thisTime.getTime()<startTime.getTime()){
                            begin_text.setText("下一场"+detailBeans[i].getName()+"开始");
//                            Log.d(TAG, "ddddddddddddddddd: " + detailBeans[i].getName());
                            break;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        });


        //点击品牌条目到详情页面
        brandAdapter.setBrandClickListener(new BrandAdapter.onBrandClickListener() {
            @Override
            public void onBrandClick(int position) {
                Intent intent=new Intent(getContext(), RecommendDetailActivity.class);
                intent.putExtra("brand_id",position);
                Log.d(TAG, "000000000000000000: " + position);
                startActivity(intent);
            }
        });

        //品牌更多推荐
        more_recommended=findViewById(R.id.more_recommended);
        more_recommended.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), RecommendMoreActivity.class));
            }
        });

        //秒杀详情页
        second_kill=findViewById(R.id.second_kill);
        second_kill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), KillDetailActivity.class));
            }
        });

        TextView tv=findViewById(R.id.sign_text);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), ProductIntroductionActivity.class));
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_shopping_mall_home_;
    }

    //自定义的图片加载器
    private class MyLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            if (j == 0) {
                Glide.with(context).load(bannerBeanList.get(0).getImage()).into(imageView);
            }else if(j == 1){
                Glide.with(context).load(bannerBeanList.get(1).getImage()).into(imageView);
            }else if(j == 2){
                Glide.with(context).load(bannerBeanList.get(2).getImage()).into(imageView);
            }else if(j == 3){
                Glide.with(context).load(bannerBeanList.get(3).getImage()).into(imageView);
            }else if(j == 4){
                Glide.with(context).load(bannerBeanList.get(4).getImage()).into(imageView);
            }
            j++;
            //5张图片7个数的原因，复制了第一张和最后一张
            //Log.d(TAG, "j: "+j);
        }
    }
}